<template>
  <n-space vertical style="width: 100%; margin-top: 20px">
    <n-layout has-sider>
      <n-layout-sider
        bordered
        collapse-mode="width"
        :collapsed-width="64"
        :width="240"
        :collapsed="collapsed"
        show-trigger
        @collapse="collapsed = true"
        @expand="collapsed = false"
      >
        <n-menu
          ref="menuInstRef"
          v-model:value="activeKey"
          @update:value="handleMenuClick"
          :collapsed="collapsed"
          :collapsed-width="64"
          :collapsed-icon-size="22"
          :options="menuOptions"
        />
      </n-layout-sider>
      <n-layout style="width: 100%; display: flex; flex-direction: column;">
        <router-view />
      </n-layout>
    </n-layout>
  </n-space>
</template>

<script lang="ts">
import type { MenuOption } from 'naive-ui'
import type { Component } from 'vue'
import { Home24Regular as Home, Settings28Regular as Setting , Toolbox12Regular as Toolbox} from '@vicons/fluent'
import { NIcon } from 'naive-ui'
import { defineComponent, h, ref, provide } from 'vue'
import { useRouter } from 'vue-router'
import type { MenuInst } from 'naive-ui'

// 渲染图标的函数
function renderIcon(icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

// 菜单选项
const menuOptions: MenuOption[] = [
  {
    label: '仪表盘',
    key: 'home',
    icon: renderIcon(Home),
    path: '/home' as string
  },
  {
    label: '设置',
    key: 'setting',
    icon: renderIcon(Setting),
    path: '/setting' as string
  },
  {
    label: '工具箱',
    key: 'toolbox',
    icon: renderIcon(Toolbox),
    children: [
      {
        label: '下载文件',
        key: 'download',
        path: '/download' as string
      }
    ]
  }
]

export default defineComponent({
  setup() {
    const router = useRouter()
    const menuInstRef = ref<MenuInst | null>(null)
    // 使用 activeKey 来绑定菜单项
    const activeKey = ref<string | null>('home')
    provide('activeKey', activeKey) // 提供给子组件访问
    provide('menuInstRef', menuInstRef) // 提供给子组件访问
    const collapsed = ref(false) // 设置菜单是否默认向右展开
    // 处理菜单点击，切换路由
    const handleMenuClick = (key: string) => {
      // 更新选中的菜单项
      activeKey.value = key
      const menuItem = menuOptions.find((item) => item.key === key)
      if (menuItem) {
        router.push(menuItem.path || '/')
      }
    }

    return {
      menuInstRef,
      activeKey, // 返回 activeKey 以供模板使用
      collapsed, // 返回 collapsed 以供模板使用
      menuOptions, // 返回菜单选项
      handleMenuClick // 返回 handleMenuClick 以供模板使用
    }
  }
})
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>
